{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "503e36ae-ca62-4f8a-880c-4fe78ff5df93",
      "metadata": {},
      "source": [
        "# How to return artifacts from a tool\n",
        "\n",
        "```{=mdx}\n",
        ":::info Prerequisites\n",
        "This guide assumes familiarity with the following concepts:\n",
        "\n",
        "- [ToolMessage](/docs/concepts/messages/#toolmessage)\n",
        "- [Tools](/docs/concepts/tools)\n",
        "- [Tool calling](/docs/concepts/tool_calling)\n",
        "\n",
        ":::\n",
        "```\n",
        "\n",
        "Tools are utilities that can be called by a model, and whose outputs are designed to be fed back to a model. Sometimes, however, there are artifacts of a tool's execution that we want to make accessible to downstream components in our chain or agent, but that we don't want to expose to the model itself.\n",
        "\n",
        "For example if a tool returns something like a custom object or an image, we may want to pass some metadata about this output to the model without passing the actual output to the model. At the same time, we may want to be able to access this full output elsewhere, for example in downstream tools.\n",
        "\n",
        "The Tool and [ToolMessage](https://api.js.langchain.com/classes/langchain_core.messages_tool.ToolMessage.html) interfaces make it possible to distinguish between the parts of the tool output meant for the model (this is the `ToolMessage.content`) and those parts which are meant for use outside the model (`ToolMessage.artifact`).\n",
        "\n",
        "```{=mdx}\n",
        ":::caution Compatibility\n",
        "\n",
        "This functionality requires `@langchain/core>=0.2.16`. Please see here for a [guide on upgrading](/docs/how_to/installation/#installing-integration-packages).\n",
        "\n",
        ":::\n",
        "```\n",
        "\n",
        "## Defining the tool\n",
        "\n",
        "If we want our tool to distinguish between message content and other artifacts, we need to specify `response_format: \"content_and_artifact\"` when defining our tool and make sure that we return a tuple of [`content`, `artifact`]:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "b9eb179d-1f41-4748-9866-b3d3e8c73cd0",
      "metadata": {},
      "outputs": [],
      "source": [
        "import { z } from \"zod\";\n",
        "import { tool } from \"@langchain/core/tools\";\n",
        "\n",
        "const randomIntToolSchema = z.object({\n",
        "  min: z.number(),\n",
        "  max: z.number(),\n",
        "  size: z.number(),\n",
        "});\n",
        "\n",
        "const generateRandomInts = tool(async ({ min, max, size }) => {\n",
        "  const array: number[] = [];\n",
        "  for (let i = 0; i < size; i++) {\n",
        "    array.push(Math.floor(Math.random() * (max - min + 1)) + min);\n",
        "  }\n",
        "  return [\n",
        "    `Successfully generated array of ${size} random ints in [${min}, ${max}].`,\n",
        "    array,\n",
        "  ];\n",
        "}, {\n",
        "  name: \"generateRandomInts\",\n",
        "  description: \"Generate size random ints in the range [min, max].\",\n",
        "  schema: randomIntToolSchema,\n",
        "  responseFormat: \"content_and_artifact\",\n",
        "});"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "0ab05d25-af4a-4e5a-afe2-f090416d7ee7",
      "metadata": {},
      "source": [
        "## Invoking the tool with ToolCall\n",
        "\n",
        "If we directly invoke our tool with just the tool arguments, you'll notice that we only get back the content part of the `Tool` output:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "id": "5e7d5e77-3102-4a59-8ade-e4e699dd1817",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Successfully generated array of 10 random ints in [0, 9].\n"
          ]
        }
      ],
      "source": [
        "await generateRandomInts.invoke({min: 0, max: 9, size: 10});"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "30db7228-f04c-489e-afda-9a572eaa90a1",
      "metadata": {},
      "source": [
        "In order to get back both the content and the artifact, we need to invoke our model with a `ToolCall` (which is just a dictionary with `\"name\"`, `\"args\"`, `\"id\"` and `\"type\"` keys), which has additional info needed to generate a ToolMessage like the tool call ID:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "id": "da1d939d-a900-4b01-92aa-d19011a6b034",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "ToolMessage {\n",
            "  lc_serializable: true,\n",
            "  lc_kwargs: {\n",
            "    content: 'Successfully generated array of 10 random ints in [0, 9].',\n",
            "    artifact: [\n",
            "      0, 6, 5, 5, 7,\n",
            "      0, 6, 3, 7, 5\n",
            "    ],\n",
            "    tool_call_id: '123',\n",
            "    name: 'generateRandomInts',\n",
            "    additional_kwargs: {},\n",
            "    response_metadata: {}\n",
            "  },\n",
            "  lc_namespace: [ 'langchain_core', 'messages' ],\n",
            "  content: 'Successfully generated array of 10 random ints in [0, 9].',\n",
            "  name: 'generateRandomInts',\n",
            "  additional_kwargs: {},\n",
            "  response_metadata: {},\n",
            "  id: undefined,\n",
            "  tool_call_id: '123',\n",
            "  artifact: [\n",
            "    0, 6, 5, 5, 7,\n",
            "    0, 6, 3, 7, 5\n",
            "  ]\n",
            "}\n"
          ]
        }
      ],
      "source": [
        "await generateRandomInts.invoke(\n",
        "  {\n",
        "    name: \"generate_random_ints\",\n",
        "    args: {min: 0, max: 9, size: 10},\n",
        "    id: \"123\", // Required\n",
        "    type: \"tool_call\", // Required\n",
        "  }\n",
        ");"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "a3cfc03d-020b-42c7-b0f8-c824af19e45e",
      "metadata": {},
      "source": [
        "## Using with a model\n",
        "\n",
        "With a [tool-calling model](/docs/how_to/tool_calling/), we can easily use a model to call our Tool and generate ToolMessages:\n",
        "\n",
        "```{=mdx}\n",
        "import ChatModelTabs from \"@theme/ChatModelTabs\";\n",
        "\n",
        "<ChatModelTabs\n",
        "  customVarName=\"llm\"\n",
        "/>\n",
        "```"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "id": "8a67424b-d19c-43df-ac7b-690bca42146c",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[\n",
            "  {\n",
            "    name: 'generateRandomInts',\n",
            "    args: { min: 1, max: 24, size: 6 },\n",
            "    id: 'toolu_019ygj3YuoU6qFzR66juXALp',\n",
            "    type: 'tool_call'\n",
            "  }\n",
            "]\n"
          ]
        }
      ],
      "source": [
        "const llmWithTools = llm.bindTools([generateRandomInts])\n",
        "\n",
        "const aiMessage = await llmWithTools.invoke(\"generate 6 positive ints less than 25\")\n",
        "aiMessage.tool_calls"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "id": "00c4e906-3ca8-41e8-a0be-65cb0db7d574",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "ToolMessage {\n",
            "  lc_serializable: true,\n",
            "  lc_kwargs: {\n",
            "    content: 'Successfully generated array of 6 random ints in [1, 24].',\n",
            "    artifact: [ 18, 20, 16, 15, 17, 19 ],\n",
            "    tool_call_id: 'toolu_019ygj3YuoU6qFzR66juXALp',\n",
            "    name: 'generateRandomInts',\n",
            "    additional_kwargs: {},\n",
            "    response_metadata: {}\n",
            "  },\n",
            "  lc_namespace: [ 'langchain_core', 'messages' ],\n",
            "  content: 'Successfully generated array of 6 random ints in [1, 24].',\n",
            "  name: 'generateRandomInts',\n",
            "  additional_kwargs: {},\n",
            "  response_metadata: {},\n",
            "  id: undefined,\n",
            "  tool_call_id: 'toolu_019ygj3YuoU6qFzR66juXALp',\n",
            "  artifact: [ 18, 20, 16, 15, 17, 19 ]\n",
            "}\n"
          ]
        }
      ],
      "source": [
        "await generateRandomInts.invoke(aiMessage.tool_calls[0])"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "ddef2690-70de-4542-ab20-2337f77f3e46",
      "metadata": {},
      "source": [
        "If we just pass in the tool call args, we'll only get back the content:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "id": "f4a6c9a6-0ffc-4b0e-a59f-f3c3d69d824d",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Successfully generated array of 6 random ints in [1, 24].\n"
          ]
        }
      ],
      "source": [
        "await generateRandomInts.invoke(aiMessage.tool_calls[0][\"args\"])"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "98d6443b-ff41-4d91-8523-b6274fc74ee5",
      "metadata": {},
      "source": [
        "If we wanted to declaratively create a chain, we could do this:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "id": "eb55ec23-95a4-464e-b886-d9679bf3aaa2",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[\n",
            "  ToolMessage {\n",
            "    lc_serializable: true,\n",
            "    lc_kwargs: {\n",
            "      content: 'Successfully generated array of 1 random ints in [1, 5].',\n",
            "      artifact: [Array],\n",
            "      tool_call_id: 'toolu_01CskofJCQW8chkUzmVR1APU',\n",
            "      name: 'generateRandomInts',\n",
            "      additional_kwargs: {},\n",
            "      response_metadata: {}\n",
            "    },\n",
            "    lc_namespace: [ 'langchain_core', 'messages' ],\n",
            "    content: 'Successfully generated array of 1 random ints in [1, 5].',\n",
            "    name: 'generateRandomInts',\n",
            "    additional_kwargs: {},\n",
            "    response_metadata: {},\n",
            "    id: undefined,\n",
            "    tool_call_id: 'toolu_01CskofJCQW8chkUzmVR1APU',\n",
            "    artifact: [ 1 ]\n",
            "  }\n",
            "]\n"
          ]
        }
      ],
      "source": [
        "const extractToolCalls = (aiMessage) => aiMessage.tool_calls;\n",
        "\n",
        "const chain = llmWithTools.pipe(extractToolCalls).pipe(generateRandomInts.map());\n",
        "\n",
        "await chain.invoke(\"give me a random number between 1 and 5\");"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "54f74020",
      "metadata": {},
      "source": [
        "## Related\n",
        "\n",
        "You've now seen how to return additional artifacts from a tool call.\n",
        "\n",
        "These guides may interest you next:\n",
        "\n",
        "- [Creating custom tools](/docs/how_to/custom_tools)\n",
        "- [Building agents with LangGraph](https://langchain-ai.github.io/langgraphjs/)"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "TypeScript",
      "language": "typescript",
      "name": "tslab"
    },
    "language_info": {
      "codemirror_mode": {
        "mode": "typescript",
        "name": "javascript",
        "typescript": true
      },
      "file_extension": ".ts",
      "mimetype": "text/typescript",
      "name": "typescript",
      "version": "3.7.2"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}